/*
 *
 * Copyright (c) 2015, joyowo. All rights reserved.
 *
 */
package com.macro.mall.exception;

import com.macro.mall.common.api.ReturnObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.sql.SQLException;

/**
 * 对系统中的异常处理，这里取名errcode和errmsg主要是参考了微信公众号API
 *
 * @author zhangsheng
 * @version 1.0
 */
@ControllerAdvice
public class ExceptionControllerAdvice extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    private static final String ERROR_COPYWRITING = "系统异常，请稍候再试.";

    @ExceptionHandler({Exception.class})
    protected ResponseEntity<Object> handleInvalidRequest(Exception e, WebRequest request) {

        ReturnObject<Void> returnObject = new ReturnObject<>();
        returnObject.setFlag(false);
        returnObject.setMsg(ERROR_COPYWRITING);
        if (e instanceof ApiException) {
            ApiException apiException = (ApiException) e;
            returnObject.setErrCode(apiException.getErrCode());
            String errMsg ="";
            if(!StringUtils.isEmpty(apiException.getErrMsg())){
                errMsg += apiException.getErrMsg();
            }
            String msg = ApiResultUtil.getInstance().getErrorInfo(apiException.getErrCode().toString());
            errMsg += msg == null ? "" : msg;
            returnObject.setMsg(errMsg);
        } else if (e instanceof DuplicateKeyException) {
            // 主键重复
            logger.error("DuplicateKeyException: ", e);
            returnObject.setErrCode("1310108");
        } else if (e instanceof BadSqlGrammarException) {
            logger.error("BadSqlGrammarException: ", e);
            returnObject.setErrCode("1310105");
        } else if (e instanceof SQLException) {
            logger.error("SQLException: ", e);
            returnObject.setErrCode("1310106");
        } else if (e instanceof NullPointerException) {
            logger.error("NullPointerException: ", e);
            returnObject.setErrCode("1310107");
        } else {
            logger.error("systemError: ", e);
            returnObject.setErrCode("1310101");
        }
        HttpHeaders headers = new HttpHeaders();
        //当设为MediaType.APPLICATION_JSON时一直出现中文乱码问题
        //根据猜测是spring-web版本问题，这里需要改成APPLICATION_JSON_UTF8
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return handleExceptionInternal(e, returnObject, headers, HttpStatus.OK, request);
    }
}
